package com.hmall.gateway.routers;

import cn.hutool.json.JSONUtil;
import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executor;

@Slf4j
@Component
@RequiredArgsConstructor
public class DynamicRouteLoader {

    private final NacosConfigManager nacosConfigManager;
    private final RouteDefinitionWriter writer;

    private final String dataId = "gateway-routes.json"; //监听的Nacos配置文件名
    private final String group = "DEFAULT_GROUP";

    private final Set<String> routeIds = new HashSet<>();
    @PostConstruct // 初始化后执行
    public void initRouterConfigListener() throws NacosException {
        // 项目启动，拉取配置，并且监听配置变更
        String configInfo = nacosConfigManager.getConfigService().getConfigAndSignListener(dataId, group, 5000, new Listener() {
            @Override
            public Executor getExecutor() {
                return null;
            }

            @Override
            public void receiveConfigInfo(String configInfo) {
                //监听配置变更，需要去更新路由表
                updateRouterConfig(configInfo);
            }
        });
        // 第一次读取配置，也需要更新到路由表
        updateRouterConfig(configInfo);
    }

    public void updateRouterConfig(String configInfo) {
        log.debug("监听到路由配置信息:{}", configInfo);
        //解析配置文件，转为RouteDefinition
        List<RouteDefinition> routeDefinitions = JSONUtil.toList(configInfo, RouteDefinition.class);
        //删除 旧的路由表
        routeIds.forEach(routeId -> {
            writer.delete(Mono.just(routeId)).subscribe();
        });
        routeIds.clear();
        // 更新路由表
        routeDefinitions.forEach(routeDefinition -> {
            //更新
            writer.save(Mono.just(routeDefinition)).subscribe();
            // 记录路由表，便于下次删除
            routeIds.add(routeDefinition.getId());
        });
    }
}
